# -*- coding: UTF-8 -*-
# @Time    : 2021/6/27 17:03
# @Author  : Sun
# @Email   : xxxxxxxxxxx@xxx.com
# @File    : base_page.py
# @software: PyCharm
# 文件注释  :
import yaml
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions

"""
封装driver类以及一些方法的二次封装
"""
class BasePage(object):

    def __init__(self, base_driver: WebDriver = None):
        if base_driver is None:
            # 利用复用模式获取cookie
            # option = webdriver.ChromeOptions()
            # option.debugger_address = '127.0.0.1:9222'
            # self.driver = webdriver.Chrome(options=option)
            # self.driver.implicitly_wait(10)
            # with open('./cookie.yaml', 'w', encoding='utf-8') as f:
            #     print(self.driver.get_cookies())
            #     # Yaml写入需要传入data&stream
            #     yaml.safe_dump(self.driver.get_cookies(), f)

            # 获取到cookie后可以放开
            self.driver = webdriver.Chrome()
            self.driver.implicitly_wait(10)
            # 窗口最大化，否则会造成元素找不到
            self.driver.maximize_window()
            # 首先要给出一个地址，否则会走默认data;
            self.driver.get('https://work.weixin.qq.com/')
            # 读取Cookie
            with open('../tests/cookie.yaml', 'r', encoding='utf-8') as f:
                cookies = yaml.safe_load(f)
            # 循环遍历cookie并传入
            for cookie in cookies:
                self.driver.add_cookie(cookie)
            self.driver.get('https://work.weixin.qq.com/wework_admin/frame')
        else:
            self.driver = base_driver

    # 重新封装find_element方法
    def find(self, by, locator):
        ele = self.driver.find_element(by, locator)
        return ele

    # 重新封装find_element().click()方法
    def find_click(self, by, locator):
        ele = self.driver.find_element(by, locator)
        ele.click()

    # 重新封装find_elements方法
    def finds(self, by, locator):
        eles = self.driver.find_elements(by, locator)
        return eles

    # 重新封装显示等待方法
    def wait_click(self, locator):
        ele = WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(locator))
        ele.click()

    # 重新封装find_element().send_keys()方法
    def find_send(self, by, locator, text):
        self.driver.find_element(by, locator).send_keys(text)

    # 重新封装execute_script方法
    def execute(self, js):
        self.driver.execute_script(js)

